/**
 * @anchor https://leetcode.cn/problems/find-median-from-data-stream/
 */

#include "../common.h"
class MedianFinder {
private:
    priority_queue<int, vector<int>, less<int>> left;
    priority_queue<int, vector<int>, greater<int>> right;
    
public:
    MedianFinder() 
    {
    }
    
    void addNum(int num) {
        if(left.size() == right.size()){
            if(left.empty() || num <= left.top()) left.push(num);
            else {
                right.push(num);
                left.push(right.top());              
                right.pop();
            }
        }
        else if(left.size() > right.size()) // left - 1 = right
        {
            if(num <= left.top()){
                left.push(num);
                right.push(left.top());
                left.pop();
            }
            else right.push(num);
        }
    }
    
    double findMedian() {
        if (left.size() > right.size()) {
            return (double)left.top();
        } 
        else {
            return (left.top() + right.top()) / 2.0;
        }
    }
};

/**
 * Your MedianFinder object will be instantiated and called as such:
 * MedianFinder* obj = new MedianFinder();
 * obj->addNum(num);
 * double param_2 = obj->findMedian();
 */